package com.tedu.pj.sys.service.impl;

import com.tedu.pj.common.exception.ServiceException;
import com.tedu.pj.common.pojo.PageObject;
import com.tedu.pj.sys.dao.SysUserDao;
import com.tedu.pj.sys.dao.SysUserRoleDao;
import com.tedu.pj.sys.pojo.SysUser;
import com.tedu.pj.sys.pojo.SysUserDeptVo;
import com.tedu.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/10/20
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserDao sysUserDao;

    @Autowired
    SysUserRoleDao sysUserRoleDao;

    @Override
    public PageObject<SysUserDeptVo> findPageObjects(String username, Integer pageCurrent) {
        if (pageCurrent == null || pageCurrent < 1) {
            throw new IllegalArgumentException("当前页码值无效");
        }
        int rowCount = sysUserDao.getRowCount(username);
        if (rowCount == 0) {
            throw new ServiceException("没有找到对应记录");
        }
        int pageSize = 10;
        int startIndex = (pageCurrent - 1) * pageSize;
        List<SysUserDeptVo> records = sysUserDao.findPageObjects(username, startIndex, pageSize);
        return new PageObject<>(pageCurrent,rowCount,  pageSize, records);
    }

    @Override
    public int updateObject(SysUser entity, Integer[] roleIds) {
        if (entity == null) {
            throw new IllegalArgumentException("保存对象不能为空");
        }
        if (StringUtils.isEmpty(entity.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (roleIds == null || roleIds.length == 0) {
            throw new IllegalArgumentException("必须为其指定角色");
        }
        int rows = sysUserDao.updateObject(entity);
        sysUserRoleDao.deleteObjectsByUserId(entity.getId());
        sysUserRoleDao.insertObjects(entity.getId(), roleIds);
        return rows;
    }

    @Override
    public int updatePassword(String password, String newPassword, String cfgPassword) {
        if (StringUtils.isEmpty(newPassword)) {
            throw new IllegalArgumentException("新密码不能为空");
        }
        if (StringUtils.isEmpty(cfgPassword)) {
            throw new IllegalArgumentException("确认密码不能为空");
        }
        if (!newPassword.equals(cfgPassword)) {
            throw new IllegalArgumentException("两次输入的密码不相等");
        }
        if (StringUtils.isEmpty(password)) {
            throw new IllegalArgumentException("原密码不能为空");
        }
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SimpleHash sh = new SimpleHash("MD5", password, user.getSalt(), 1);
        if (!user.getPassword().equals(sh.toHex())) {
            throw new IllegalArgumentException("原密码不正确");
        }
        String salt = UUID.randomUUID().toString();
        sh = new SimpleHash("MD5", newPassword, salt, 1);
        int rows = sysUserDao.updatePassword(sh.toHex(),
                salt, user.getId());
        if (rows == 0) {
            throw new ServiceException("修改失败");
        }
        return rows;
    }

    @Override
    public Map<String, Object> findObjectById(Integer userId) {
        //1.合法性验证
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("参数数据不合法,userId=" + userId);
        }
        SysUserDeptVo user = sysUserDao.findObjectById(userId);
        if (user == null) {
            throw new ServiceException("此用户已经不存在");
        }
        List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roleIds", roleIds);
        return map;
    }

    @Override
    public int saveObject(SysUser entity, Integer[] roleIds) {
        long start = System.currentTimeMillis();
        if (entity == null) {
            throw new IllegalArgumentException("保存对象不能为空");
        }
        if (StringUtils.isEmpty(entity.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (StringUtils.isEmpty(entity.getPassword())) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (roleIds == null || roleIds.length == 0) {
            throw new IllegalArgumentException("至少要为用户分配角色");
        }
        String source = entity.getPassword();
        String salt = UUID.randomUUID().toString();
        SimpleHash sh = new SimpleHash( // Shiro 框架
                "MD5", //algorithmName 算法
                source, //原密码
                salt, //盐值
                1); //hashIterations表示加密次数
        entity.setSalt(salt);
        entity.setPassword(sh.toHex());
        int rows = sysUserDao.insertObject(entity);
        sysUserRoleDao.insertObjects(entity.getId(), roleIds);
        long end = System.currentTimeMillis();
        return rows;
    }

    @Override
    public int validById(Integer id, Integer valid) {
        if (id == null || id <= 0) {
            throw new ServiceException("参数不合法,id=" + id);
        }
        if (valid == null || (valid != 1 && valid != 0)) {
            throw new ServiceException("参数不合法,valid=" + valid);
        }
        int rows = sysUserDao.validById(id, valid, "admin");
        if (rows == 0) {
            throw new ServiceException("此记录可能已经不存在");
        }
        return rows;
    }
}
